<?php


namespace app\partneradmin\controller;


use app\partneradmin\model\PartnerAdmin;
use app\common\controller\partneradmin\Base;
use app\partneradmin\model\Partner;
use super\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\partneradmin\model\CustomerServicePersonnel;

class Customerservicegroup extends Base
{

    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\partneradmin\model\CustomerServiceGroup();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $name = $this->request->post('name', '');
            $switch = $this->request->post('switch', '');
            $partner_id = $this->admin['partner_id'];
            $where['partner_id'] = $partner_id;
            if ($switch != '') {
                $where['switch'] = $switch;
            }
            if ($name != '') {
                $where['name'] = ['like', '%' . $name . '%'];
            }
            //如果是组长则只展示组长所在组数据
            if ($this->admin['rule'] == 1) {
                $adminCustomerServiceInfo = $this->getCustomerServiceInfo();
                $customerServiceGroupId = $adminCustomerServiceInfo['customer_service_personnel_info']['customer_service_group_id'];
                $where['id'] = $customerServiceGroupId;
            }
            $where['is_del'] = 0;
            $partner = new Partner();
            $partnerList = $partner->getPartnerAll([], 'id,name,app_id');
            $partnerList = array_column($partnerList, null, 'id');
            $list = $this->model
                ->field('*')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select();
            foreach ($list as $key => $value) {
                $value['partner_name'] = empty($partnerList[$value['partner_id']]) ? '' : $partnerList[$value['partner_id']]['name'];
                //显示每日可分配跟已分配
                //取出所有客服组下的客服账号
                $accountModel = new \app\partneradmin\model\CustomerServiceAccount();
                $accountList = $accountModel->with(['CustomerServiceAccountMiddle'])->where([
                    'customer_service_group_id' => $value['id'],
//                    'status' => 1,
                    'switch' => 1
                ])
                    ->select();
                $value['assigned_user_num'] = Statistics::getAssignedUserNum($accountList);
                $list[$key] = $value;
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 重构详情接口
     * @param string $ids
     */
    public function details($ids = "")
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('未查询到数据！', '', [], 404);
        }
        //客服组查找组长
        $customerServicePersonnel = new CustomerServicePersonnel();
        $personnelInfoWhere = [
            'pid' => 0,
            'customer_service_group_id' => $ids,
            'is_del' => 0
        ];
        $personnelInfo = $customerServicePersonnel->field('id,name,phone,email,partner_admin_id')->where($personnelInfoWhere)->find();
        if (empty($personnelInfo)) {
            $this->error('获取客服组下组长信息失败');
        }
        //通过组长查找登陆账号
        $partneradmin = new PartnerAdmin();
        $partneradminInfoWhere = [
            'id' => $personnelInfo['partner_admin_id']
        ];
        $partneradminInfo = $partneradmin->where($partneradminInfoWhere)->find();
        if (empty($partneradminInfo)) {
            $this->error('获取客服组下组长登陆信息失败');
        }
        $row['personnel_id'] = $personnelInfo['id'];
        $row['personnel_name'] = $personnelInfo['name'];
        $row['phone'] = $personnelInfo['phone'];
        $row['email'] = $personnelInfo['email'];
        $row['partner_admin_id'] = $partneradminInfo['id'];
        $row['username'] = $partneradminInfo['username'];
        $this->success('详情数据', '', $row);
    }

    /**
     * 重写新增
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    if ($this->admin['rule'] == 1 || $this->admin['rule'] == 2) {
                        $this->error('添加失败,无权限');
                    }
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $params['create_time'] = time();
                    //检查合作方是否有可分配数量
                    if (!empty($params['distribution_user_num'])) {
                        $partner = Partner::get($params['partner_id']);
                        $assignedNum = $this->model->where('partner_id', '=', $params['partner_id'])->sum('distribution_user_num');
                        $surplusNum = $partner['distribution_user_num'] - $assignedNum;
                        if ($params['distribution_user_num'] > $surplusNum) {
                            $this->error('合作方剩余可分数为' . $surplusNum);
                        }
                    }
                    $setData = [
                        'name' => $params['name'],
                        'partner_id' => $params['partner_id'],
                        'distribution_user_num' => empty($params['distribution_user_num']) ? 0 : $params['distribution_user_num'],
                        'create_time' => time(),
                    ];
                    $result = $this->model->allowField(true)->insertGetId($setData);
                    //添加成功后执行组长添加操作
                    //添加客服人员登录账号
                    $rule = 1;
                    $salt = Random::alnum();
                    $setpartneradminData = [
                        'username' => $params['username'],
                        'partner_id' => $params['partner_id'],
                        'rule' => $rule,
                        'salt' => $salt,
                        'password' => md5(md5($params['password']) . $salt),
                        'admin_id' => $this->admin['id'],
                        'create_time' => time(),
                    ];
                    //查询登陆账号是否存在

                    $partneradmin = new PartnerAdmin();
                    $partneradminInfo = $partneradmin->where('username', '=', $setpartneradminData['username'])->find();
                    if ($partneradminInfo) {
                        $this->error('添加失败,登录账号已存在');
                    }
                    $partneradminId = $partneradmin->insertGetId($setpartneradminData);
                    //添加客服组长
                    $customerServicePersonnel = new CustomerServicePersonnel();
                    $customerServicePersonnelInfo = $customerServicePersonnel->where('name','=',$params['personnel_name'])->find();
                    if ($customerServicePersonnelInfo) {
                        $this->error('添加失败,客服组长名字已存在');
                    }
                    $setData = [
                        'name' => $params['personnel_name'],
                        'phone' => $params['phone'],
                        'email' => empty($params['email']) ? '' : $params['email'],
                        'pid' => 0,
                        'customer_service_group_id' => $result,
                        'partner_id' => $params['partner_id'],
                        'partner_admin_id' => $partneradminId,
                    ];

                    $customerServicePersonnel->save($setData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 重构编辑方法
     * @param null $ids
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.edit';
                        $row->validateFailException(true)->validate($validate);
                    }
                    //检查合作方是否有可分配数量
                    if (!empty($params['distribution_user_num'])) {
                        $partner = Partner::get($params['partner_id']);
                        $assignedNum = $this->model->where('partner_id', '=', $params['partner_id'])->where('id', 'neq', $ids)->sum('distribution_user_num');
                        $surplusNum = $partner['distribution_user_num'] - $assignedNum;
                        if ($params['distribution_user_num'] > $surplusNum) {
                            $this->error('合作方剩余可分数为' . $surplusNum);
                        }
                    }
                    $result = $row->allowField(true)->isUpdate(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 单独获取客服组列表根据合作方id
     * @param null $partner_id
     */
    public function getCustomerServiceGroupAllByPartnerId($partner_id = null)
    {
        if (empty($partner_id)) {
            $this->error('获取失败，请选择合作方');
        }
        $where = [
            'is_del' => 0,
            'switch' => 1
        ];
        $list = $this->model
            ->field('id,name')
            ->where($where)
            ->select();
        $data = [
            'list' => $list
        ];
        $this->success('列表', '', $data);
    }

}